<template>
  <!-- 最外层wrap -->
  <div>
    <!-- 标题 -->
    <el-dialog
      v-bind="$attrs"
      :visible.sync="showDialog"
      @close="onClose"
      title="注册"
    >
      <!-- 主体部分 -->
      <el-row :gutter="15">
        <!-- 表单 -->
        <el-form ref="elForm" :model="user" :rules="rules" size="medium" label-width="100px">
          <!-- 表单项：用户头像 -->
          <el-col :span="21">
            <!-- 用户头像 -->
            <el-form-item :label="isStudent?'学生':'教师'">
              <!-- 头衔缩略图 -->
              <pan-thumb :image="image" />
            </el-form-item>
          </el-col>
          <slot name="id"></slot>
          <!-- 表单项：学号/工号 -->
          <el-col :span="12">
            <el-form-item label="工号/学号" prop="id">
              <el-input
                v-model="user.id"
                oninput="value=value.replace(/[^\d]/g,'')"
                placeholder="请输入工号或学号"
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 表单项：姓名 -->
          <el-col :span="12">
            <el-form-item label="姓名" prop="username">
              <el-input
                v-model="user.username"
                placeholder="请输入姓名"
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 表单项：身份 -->
          <el-col :span="12">
            <el-form-item label="身份" prop="type">
              <el-select v-model="user.type" placeholder="请选择身份" clearable :style="{width: '100%'}">
                <el-option
                  v-for="item in TypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 表单项：昵称 -->
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="user.nickname"
                placeholder="请输入昵称"
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 表单项：性别 -->
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="user.sex" size="medium">
                <el-radio
                  v-for="(item, index) in sexOptions"
                  :key="index"
                  :label="item.value"
                  :disabled="item.disabled"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 表单项：密码 -->
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="user.password"
                placeholder="请输入密码"
                clearable
                show-password
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 表单项：院系和专业 -->
          <el-col :span="12">
            <el-form-item v-model="DepartmentValue" label="院系和专业" prop="departmentId">
              <el-cascader
                :options="departmentList"
                @change="handleChange"
                :style="{width: '100%'}"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <!-- 表单项：手机号 -->
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                v-model="user.phoneNumber"
                placeholder="请输入手机号"
                oninput="value=value.replace(/[^\d]/g,'')"
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 表单项：生日 -->
          <el-col :span="12">
            <el-form-item
              label="生日"
              :rules="[
                  { required: true, message: '请选择生日', trigger: ['blur','change'] },
                  { validator: validateDate, trigger: ['blur', 'change'] }
                ]"
              prop="birth"
            >
              <el-date-picker
                v-model="user.birth"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                placeholder="请选择生日"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 可选表单项：入学年份 -->
          <el-col :span="12">
            <el-form-item
              label="入学时间"
              :rules="[
                  { required: isStudent, message: '请选择入学年份', trigger: ['blur','change'] },
                  { validator: validateDate, trigger: ['blur', 'change'] }
                ]"
              prop="admissionTime"
            >
              <el-date-picker
                v-model="user.admissionTime"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                :disabled="!isStudent"
                placeholder="请选择入学时间"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <!-- 提交表单/取消 -->
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { createNamespacedHelpers } from "vuex";
import PanThumb from "../components/avatar-upload/PanThumb";
import { register } from "../api/user";
import { getDepartmentList } from "../api/department";
const { mapState:departmentMapState, mapActions:departmentMapActions } = createNamespacedHelpers("department");
const { mapState:userMapState, mapActions:userMapActions } = createNamespacedHelpers("user");
export default {
  inheritAttrs: false,
  components: {
    PanThumb,
  },
  props: {
    addOrUpdateVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      image:
        "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3857377881,4096200583&fm=26&gp=0.jpg",
      user: {
        id: null,
        type: undefined,
        avatar: null,
        username: undefined,
        departmentId: undefined,
        majorId: undefined,
        nickname: undefined,
        sex: 0,
        password: undefined,
        phoneNumber: undefined,
        birth: '2000-01-01',
        admissionTime: '2018-9-1'
      },
      showDialog: false,
      rules: {
        id: [
          {
            required: true,
            message: "请输入学号或工号",
            trigger: ["blur", "change"]
          },
          {
            min: 6,
            max: 14,
            message: "内容在6~14位之间",
            trigger: ["blur", "change"]
          }
        ],
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: ["blur", "change"]
          },
          {
            min: 2,
            max: 6,
            message: "姓名在2~6位之间",
            trigger: ["blur", "change"]
          }
        ],
        departmentId: [
          {
            required: true,
            message: "请选择院系和专业",
            trigger: ["blur", "change"]
          }
        ],
        majorId: [
          {
            required: true,
            message: "请选择专业",
            trigger: ["blur", "change"]
          }
        ],
        nickname: [
          {
            required: true,
            message: "请输入昵称",
            trigger: ["blur", "change"]
          },
          {
            min: 2,
            max: 8,
            message: "昵称在2~8位之间",
            trigger: ["blur", "change"]
          }
        ],
        sex: [
          {
            required: true,
            message: "请选择性别",
            trigger: ["blur", "change"]
          }
        ],
        type: [
          {
            required: true,
            message: "请选择身份",
            trigger: ["blur", "change"]
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"]
          },
          {
            min: 6,
            max: 14,
            message: "姓名在6~14位之间",
            trigger: ["blur", "change"]
          }
        ],
        phoneNumber: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["blur", "change"]
          },
          {
            min: 6,
            max: 11,
            message: "电话号码在6~11位之间",
            trigger: ["blur", "change"]
          }
        ]
      },
      isStudent: true,
      TypeOptions: [
        {
          value: "1",
          label: "学生"
        },
        {
          value: "2",
          label: "教师"
        }
      ],
      avatarfileList: [],
      sexOptions: [
        {
          label: "帅哥",
          value: 0
        },
        {
          label: "美女",
          value: 1
        },
        {
          label: "保密",
          value: 2
        }
      ],
      // 院系和专业双向绑定的变量
      DepartmentValue: [],
      // // // 院系和专业选项
      // departmentList: []
    };
  },
  computed: {
    userType() {
      return this.user.type;
    },
    ...departmentMapState({
      departmentList:(state) => state.departmentList,
      
    }),
    ...userMapState({
      res:(state) => state.registerRes
    })
  },
  watch: {
    addOrUpdateVisible(oldVal, newVal) {
      this.showDialog = this.addOrUpdateVisible;
    },
    userType(newVal, oldVal) {
      if (newVal == 1) {
        this.isStudent = true;
        this.image =
          "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3857377881,4096200583&fm=26&gp=0.jpg";
      } else {
        this.isStudent = false;
        this.image =
          "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2957226749,2375869085&fm=26&gp=0.jpg";
      }
    }
  },
  mounted() {
    this.getDepartmentList();
  },
  methods: {
    // 日期效验
    validateDate(rule, value, callback) {
      if (value) {
        let timestamp = new Date(value).getTime();
        let now = new Date().getTime();
        if (timestamp >= now) {
          callback(new Error("超出指定时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 打开页面
    onOpen() {},
    // 关闭页面表单处理
    onClose() {
      this.$refs["elForm"].resetFields(), this.$emit("changeShow", "false");
    },
    // 关闭页面
    close() {
      this.$emit("update:visible", false), this.$emit("changeShow", "false");
    },
    // 部门选择触发函数
    handleChange(value) {
      this.user.departmentId = value[0];
      this.user.majorId = value[1];
    },

    // 关闭注册组件回调函数
    handleClose() {
      // 子组件调用父组件方法，并传递参数
      this.$emit("changeShow", "false");
    },

    // 提交表单
    handelConfirm() {
      this.$refs["elForm"].validate(valid => {
        if (!valid) return;
        else this.post(this.user);
      });
    },
    // 发送注册请求
    async post(user) {
      await this.registerPost(user);
      console.log(this.res);
      if (this.res.code == 20000) {
        this.$notify.success({
          title: "操作成功",
          message: "注册成功"
        });
        // 关闭
        this.$emit("changeShow", "false");
        // 清空用户信息
        // this.user = {};
      } else {
        return this.$message.error("注册失败:" + this.res.message);
      }
    },

    // 数据处理接口
    // getDepartmentList：获取院系和专业列表
    ...departmentMapActions(['getDepartmentList']),
    ...userMapActions(['registerPost'])
  }
};
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
